/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controladores;

import controladores.exceptions.NonexistentEntityException;
import entidades.Vehiculo;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author Pablo
 */
public class VehiculoJpaController implements Serializable {

    public static final int CHASIS = 1;
    public static final int NRO_UNIDAD = 2;
    public static final int NRO_CHAPA = 3;
    public static final int DESCRIPCION = 4;
    public static final int CHOFER = 5;
    
    public VehiculoJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Vehiculo vehiculo) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(vehiculo);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Vehiculo vehiculo) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            vehiculo = em.merge(vehiculo);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = vehiculo.getId();
                if (findVehiculo(id) == null) {
                    throw new NonexistentEntityException("The vehiculo with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Vehiculo vehiculo;
            try {
                vehiculo = em.getReference(Vehiculo.class, id);
                vehiculo.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The vehiculo with id " + id + " no longer exists.", enfe);
            }
            em.remove(vehiculo);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Vehiculo> findVehiculoEntities() {
        return findVehiculoEntities(true, -1, -1);
    }

    public List<Vehiculo> findVehiculoEntities(int maxResults, int firstResult) {
        return findVehiculoEntities(false, maxResults, firstResult);
    }

    private List<Vehiculo> findVehiculoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Vehiculo.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Vehiculo findVehiculo(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Vehiculo.class, id);
        } finally {
            em.close();
        }
    }

    public int getVehiculoCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Vehiculo> rt = cq.from(Vehiculo.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
    //Mis Metodos
    public List<Vehiculo> getVehiculosLikeDescripcion(String str) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "SELECT a FROM Vehiculo a WHERE a.descripcion LIKE :s";
            Query query = em.createQuery(jpql);
            query.setParameter("s", "%"+str+"%");
            result = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (result);
    }
    
    public List<Vehiculo> getVehiculosLikeNroUnidad(String str) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "SELECT a FROM Vehiculo a WHERE a.nro_unidad LIKE :s";
            Query query = em.createQuery(jpql);
            query.setParameter("s", "%"+str+"%");
            result = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (result);
    }
    
    public List<Vehiculo> getVehiculosPorDescripcion(String doc) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "SELECT a FROM Vehiculo a WHERE a.descripcion =:doc";
            Query query = em.createQuery(jpql);
            query.setParameter("doc", doc);
            result = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (result);
    }
    
    public List<Vehiculo> getVehiculosLike(String value, int parametro) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "";
            switch(parametro){
                case VehiculoJpaController.NRO_CHAPA:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.chapa LIKE :nro";
                    break;
                case VehiculoJpaController.CHASIS:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.nro_chasis LIKE :nro";
                    break;
                case VehiculoJpaController.NRO_UNIDAD:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.nro_unidad LIKE :nro";
                    break;
                case VehiculoJpaController.DESCRIPCION:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.descripcion LIKE :nro";
                    break; 
                case VehiculoJpaController.CHOFER:
                    jpql = "SELECT a FROM Vehiculo a JOIN a.chofer ch WHERE ch.apellido LIKE :nro";                    
                    break;     
            }
            
            Query query = em.createQuery(jpql);
            query.setParameter("nro", "%"+value+"%");
            result = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (result);
    }
    
   
    public boolean yaExiste(String value, int parametro, Long id_excepcion) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "";
            switch(parametro){
                case VehiculoJpaController.NRO_CHAPA:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.chapa =:nro";
                    break;
                case VehiculoJpaController.CHASIS:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.nro_chasis =:nro";
                    break;
                case VehiculoJpaController.NRO_UNIDAD:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.nro_unidad =:nro";
                    break;
                case VehiculoJpaController.DESCRIPCION:
                    jpql = "SELECT a FROM Vehiculo a WHERE a.descripcion =:nro";
                    break;    
            }
            
            Query query = em.createQuery(jpql);
            query.setParameter("nro", value);
            result = query.getResultList();
            if(result.isEmpty())
                return false;
            else{
               for(Vehiculo v: result){
                   if(v.getId().equals(id_excepcion))
                       return false;
               }
               return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    
    public List<Vehiculo> getVehiculosPor(String value, String parametro) {
        EntityManager em = getEntityManager();
        List<Vehiculo> result = null;
        try {
            String jpql = "";
            switch(parametro){
                case "Propietario":                    
                    jpql = "SELECT ve FROM Vehiculo ve JOIN ve.propietario pro WHERE pro.descripcion =:valor";
                    break;
                case "Vehículos externos":
                    jpql = "SELECT ve FROM Vehiculo ve JOIN ve.propietario pro WHERE pro.descripcion <> 'HORMICAT S.A'";
                    break;
                case "Obra":
                    jpql = "SELECT ve FROM Vehiculo ve JOIN ve.obra ob WHERE ob.descripcion =:valor";
                    break;
                case "Categoria":
                    jpql = "SELECT ve FROM Vehiculo ve JOIN ve.categoria cat WHERE cat.descripcion =:valor";
                    break;    
            }
            
            Query query = em.createQuery(jpql);
            if(!parametro.equals("Vehículos externos"))
                query.setParameter("valor", value);
            result = query.getResultList();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return (result);
    }
    
    
}
